#include "Game.hh" // 包含游戏头文件，定义了Game类和相关功能 / Include Game header, defines Game class and related functions
#include <iostream> // 包含输入输出库，用于显示信息和读取用户输入 / Include input-output library for displaying info and reading user input

// 在村庄休息：恢复玩家生命值（如果需要）
// Rest in village: Restore player's health (if needed)
void Game::restInVillage() {
    if (player->getHealth() < player->getMaxHealth() && !player->isInvincible()) { // 检查玩家生命值是否未满且不是无敌状态 / Check if player's health is not full and not invincible
        unsigned newHealth = player->getHealth() + 5; // 计算新生命值：当前生命值加5 / Calculate new health: current health plus 5
        if (newHealth > player->getMaxHealth()) newHealth = player->getMaxHealth(); // 如果新生命值超过最大值，限制为最大值 / If new health exceeds max, cap at max
        // 创建一个新玩家对象，保留原有属性但更新生命值 / Create a new player object, keeping original attributes but updating health
        Character* newPlayer = new Character(player->getName(), player->getDescription(), newHealth, 
                                            player->getMaxHealth(), player->getAttack(), player->getDefense(), 
                                            player->isInvincible());
        for (Item* item : player->getInventory()) { // 遍历当前玩家的背包 / Loop through current player's inventory
            newPlayer->addToInventory(item->clone()); // 复制每个物品到新玩家的背包 / Copy each item to new player's inventory
        }
        if (player->getEquippedWeapon() != "None") { // 如果当前玩家装备了武器 / If current player has a weapon equipped
            for (size_t i = 0; i < newPlayer->getInventory().size(); ++i) { // 遍历新玩家的背包 / Loop through new player's inventory
                if (newPlayer->getInventory()[i]->name == player->getEquippedWeapon()) { // 找到相同的武器 / Find the same weapon
                    newPlayer->equipItem(i); // 装备该武器 / Equip the weapon
                    break; // 退出循环 / Exit loop
                }
            }
        }
        if (player->getEquippedArmor() != "None") { // 如果当前玩家装备了盔甲 / If current player has armor equipped
            for (size_t i = 0; i < newPlayer->getInventory().size(); ++i) { // 遍历新玩家的背包 / Loop through new player's inventory
                if (newPlayer->getInventory()[i]->name == player->getEquippedArmor()) { // 找到相同的盔甲 / Find the same armor
                    newPlayer->equipItem(i); // 装备该盔甲 / Equip the armor
                    break; // 退出循环 / Exit loop
                }
            }
        }
        delete player; // 释放旧玩家对象的内存 / Free memory of old player object
        player = newPlayer; // 将玩家指针指向新玩家对象 / Point player pointer to new player object
        addMessage("[Turn " + std::to_string(turnCount) + "] You rested in the village, restored 5 health!"); // 添加消息：休息恢复了5点生命值 / Add message: Restored 5 health by resting
    } else { // 如果生命值已满或玩家无敌 / If health is full or player is invincible
        addMessage("[Turn " + std::to_string(turnCount) + "] You rested, but your health is full or you are invincible!"); // 添加消息：休息无效果 / Add message: Rest had no effect
    }
}

// 与村民交易：用物品交换其他物品或离开村庄
// Trade with villager: Exchange items with villager or leave village
void Game::tradeWithVillager() {
    std::cout << "———— Villager Trading ————\n"; // 打印交易菜单标题 / Print trading menu title
    std::cout << "1. Trade Stick for Bread (requires 1 Stick)\n"; // 选项1：用1根木棍换面包 / Option 1: Trade 1 Stick for Bread
    std::cout << "2. Trade 2 Bones for Crossbow\n"; // 选项2：用2根骨头换弩 / Option 2: Trade 2 Bones for Crossbow
    std::cout << "3. Leave Village\n"; // 选项3：离开村庄 / Option 3: Leave village
    std::cout << "Enter choice (1-3): "; // 提示用户输入选项（1-3） / Prompt user to enter choice (1-3)

    std::string input; // 定义字符串变量存储用户输入 / Define string variable to store user input
    int tradeChoice; // 定义整数变量存储用户选择的交易选项 / Define integer variable to store chosen trade option
    while (true) { // 进入循环，直到用户输入有效数字 / Enter loop until user enters valid number
        std::getline(std::cin, input); // 读取用户输入的整行 / Read entire line of user input
        if (validateInput(input, tradeChoice, 3)) break; // 如果输入是1-3，退出循环 / If input is 1-3, exit loop
        std::cout << "Invalid input! Please enter a number between 1 and 3: "; // 提示输入无效，要求重新输入 / Prompt invalid input, ask to retry
    }

    if (tradeChoice == 1) { // 如果选择选项1：用木棍换面包 / If option 1 chosen: Trade Stick for Bread
        if (player->removeItem("Stick")) { // 尝试从背包移除1根木棍 / Try to remove 1 Stick from inventory
            player->addToInventory(new Item("Bread", "A villager's gift", 0, 0, 10)); // 添加面包（+10生命值）到背包 / Add Bread (+10 health) to inventory
            addMessage("[Turn " + std::to_string(turnCount) + "] You traded a Stick for Bread!"); // 添加消息：交易成功 / Add message: Trade successful
        } else { // 如果背包中没有木棍 / If no Stick in inventory
            addMessage("[Turn " + std::to_string(turnCount) + "] You don't have a Stick!"); // 添加消息：缺少木棍 / Add message: No Stick available
        }
    } else if (tradeChoice == 2) { // 如果选择选项2：用2根骨头换弩 / If option 2 chosen: Trade 2 Bones for Crossbow
        if (player->removeItem("Bone", 2)) { // 尝试从背包移除2根骨头 / Try to remove 2 Bones from inventory
            player->addToInventory(new Item("Crossbow", "A pillager's weapon", 10, 0, 0)); // 添加弩（+10攻击力）到背包 / Add Crossbow (+10 attack) to inventory
            addMessage("[Turn " + std::to_string(turnCount) + "] You traded 2 Bones for a Crossbow!"); // 添加消息：交易成功 / Add message: Trade successful
        } else { // 如果背包中骨头不足 / If not enough Bones in inventory
            addMessage("[Turn " + std::to_string(turnCount) + "] You don't have enough Bones!"); // 添加消息：骨头不足 / Add message: Not enough Bones
        }
    } else { // 如果选择选项3：离开村庄 / If option 3 chosen: Leave village
        inVillage = false; // 设置玩家不再在村庄 / Set player as no longer in village
        addMessage("[Turn " + std::to_string(turnCount) + "] You left the village."); // 添加消息：离开村庄 / Add message: Left the village
    }
}